package com.devinsor.spring.framework.webmvc.servlet;

import com.devinsor.spring.framework.annotation.Controller;
import com.devinsor.spring.framework.annotation.RequestMapping;
import com.devinsor.spring.framework.context.ApplicationContext;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: com.elvis.demo-v1
 * @description: 控制器
 * @author: JackRen
 * @create: 2020-05-13 14:26
 **/
public class DispatcherServlet extends HttpServlet {

    private ApplicationContext applicationContext;

    private List<HandlerMapping> handlerMappings = new ArrayList<HandlerMapping>();

    private Map<HandlerMapping,HandlerAdapter> handlerAdapters = new HashMap<HandlerMapping, HandlerAdapter>();

    private List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    //运行阶段
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //6、根据URL完成方法的调度
        try {
            doDispatch(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String,Object> model = new HashMap<String,Object>();
            model.put("detail", "500 Exception Detail");
            model.put("stackTrace", Arrays.toString(e.getStackTrace()));
            try {
                processDispatchResult(req,resp,new ModelAndView("500", model));
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

    }
/**
  * @author JackRen
  * @date 2020/5/13
 * 方法调度
*/
    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        //1、根据URL拿到对应的HandlerMapping对象
        HandlerMapping handler = getHandler(req);

        if(null == handler){
            processDispatchResult(req,resp,new ModelAndView("404"));
            return;
        }

        //2、根据HandlerMapping获得一个HandlerAdapter
        HandlerAdapter ha = getHandlerAdapter(handler);

        //3、根据HandlerAdapter拿到一个ModelAndView
        ModelAndView mv = ha.handle(req,resp,handler);

        //4、根据ViewResolver根据ModelAndView去拿到View
        processDispatchResult(req,resp,mv);

    }


    private HandlerAdapter getHandlerAdapter(HandlerMapping handler) {
        if(this.handlerAdapters.isEmpty()){return null;}
        return this.handlerAdapters.get(handler);
    }

    //404 、500 、自定义模板
    private void processDispatchResult(HttpServletRequest req, HttpServletResponse resp, ModelAndView mv) throws Exception {
        if(null == mv){ return; }

        if(this.viewResolvers.isEmpty()){return;}

        for (ViewResolver viewResolver : this.viewResolvers) {
            View view = viewResolver.resolveViewName(mv.getViewName());
            view.render(mv.getModel(),req,resp);
            return;
        }
    }

    private HandlerMapping getHandler(HttpServletRequest req) {
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replaceAll(contextPath,"").replaceAll("/+","/");

        for (HandlerMapping handlerMapping : this.handlerMappings) {
            Matcher matcher = handlerMapping.getPattern().matcher(url);
            if(!matcher.matches()){continue;}
            return handlerMapping;
        }

        return null;
    }

    /**
      * @author JackRen
      * @date 2020/5/13
     * 初始化阶段
    */
    @Override
    public void init(ServletConfig config) throws ServletException {
        applicationContext = new ApplicationContext(config.getInitParameter("contextConfigLocation"));
        //===========  MVC  ============
        //5、初始化HandlerMapping
//        doInitHandlerMapping();
        //mvc 九大组件
        initStrategies(applicationContext);
        System.out.println("MVC Spring framework is init.");
    }

    private void initStrategies(ApplicationContext applicationContext) {
        //handlerMapping
        initHandlerMapping(applicationContext);
        //初始化参数适配器
        initHandlerAdapters(applicationContext);
        //初始化试图转换器
        initViewResolvers(applicationContext);
    }

    private void initViewResolvers(ApplicationContext applicationContext) {
        //模板引擎的根路径
        String tempateRoot = applicationContext.getConfig().getProperty("templateRoot");
        String templateRootPath = this.getClass().getClassLoader().getResource(tempateRoot).getFile();

        File templateRootDir = new File(templateRootPath);
        for (File file : templateRootDir.listFiles()) {
            this.viewResolvers.add(new ViewResolver(tempateRoot));
        }
    }

    private void initHandlerAdapters(ApplicationContext applicationContext) {
        for (HandlerMapping handlerMapping : handlerMappings) {
            this.handlerAdapters.put(handlerMapping,new HandlerAdapter());
        }
    }

    private void initHandlerMapping(ApplicationContext applicationContext){
        if(applicationContext.getBeanDefinitionCount() == 0){
            return;
        }
        String [] beanNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            Object instance = applicationContext.getBean(beanName);
            Class<?> clazz = instance.getClass();
            if(!clazz.isAnnotationPresent(Controller.class)){ continue; }
            String baseUrl = "";
            if(clazz.isAnnotationPresent(RequestMapping.class)){
                RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
                baseUrl = requestMapping.value();
            }
            //默认只获取public方法
            for (Method method : clazz.getMethods()) {
                if(!method.isAnnotationPresent(RequestMapping.class)){continue;}
                RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                String regex = ("/" + baseUrl + "/" + requestMapping.value().replaceAll("\\*",".*")).replaceAll("/+","/");
                Pattern pattern = Pattern.compile(regex);
                handlerMappings.add(new HandlerMapping(pattern,instance,method));
                System.out.println("Mapped " + regex + "," + method);
            }
        }

    }
}
